<template>
  <div class="app-container calendar-list-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input clearable class="filter-item" style="width: 200px;" placeholder="请输入订单编号" v-model="listQuery.orderSn">
      </el-input>
      <el-input clearable class="filter-item" style="width: 200px;" placeholder="请输入收货人姓名" v-model="listQuery.consignee">
      </el-input>
      <el-input clearable class="filter-item" style="width: 200px;" placeholder="请输入收货人联系方式" v-model="listQuery.mobile">
      </el-input>
      <el-select class="filter-item" v-model="listQuery.orderStatus" placeholder="请选择订单状态">
        <el-option v-for="item in status" :key="item.value" :label="item.label" :value="item.value"> </el-option>
      </el-select>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-download" @click="handleDownload" :loading="downloadLoading">导出</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table size="small" :data="list" v-loading="listLoading" element-loading-text="正在查询中。。。" border fit highlight-current-row>

      <el-table-column type="expand">
        <template slot-scope="props">
        </template>
      </el-table-column>

      <el-table-column align="center" width="100px" label="订单ID" prop="id" sortable>
      </el-table-column>

      <el-table-column align="center" min-width="100px" label="用户ID" prop="userId">
      </el-table-column>
      <el-table-column align="center" min-width="100px" label="收货人" prop="consignee">
      </el-table-column>
      <el-table-column align="center" min-width="100px" label="联系方式" prop="mobile">
      </el-table-column>

      <el-table-column align="center" min-width="100px" label="订单编号" prop="orderSn">
      </el-table-column>
      <el-table-column align="center" min-width="100px" label="实际费用" prop="actualPrice">
      </el-table-column>
      <el-table-column align="center" min-width="100px" label="订单状态" prop="orderStatusText">
        <template slot-scope="scope">
          <el-tag :type="scope.row.orderStatus =='203'?  'error':'success' ">{{scope.row.orderStatusText}}</el-tag>
        </template>
      </el-table-column>

      <!--  <el-table-column align="center" min-width="100px" label="是否删除" prop="deleted">
        <template slot-scope="scope">
          <el-tag :type="scope.row.deleted ?  'error':'success' ">{{scope.row.deleted ? '已删除':'未删除'}}</el-tag>
        </template>
      </el-table-column> -->

      <el-table-column align="center" label="操作" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="orderDetail(scope.row)">订单详情</el-button>
          <el-button v-if="scope.row.orderStatus=='201'" type="primary" size="mini" @click="handleSend(scope.row)">发货</el-button>
          <el-button v-if="scope.row.orderStatus=='301'" type="primary" size="mini" @click="handleSend(scope.row)">发货信息</el-button>
          <el-button v-if="scope.row.orderStatus=='301'" type="primary" size="mini" @click="handleRecv(scope.row)">收货</el-button>
          <el-button v-if="scope.row.orderStatus=='202'" type="danger" size="mini" @click="handleRefound(scope.row)">退款</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 发货对话框 -->
    <el-dialog title="发货" :visible.sync="sendDialogFormVisible">
      <el-form ref="dataForm" :model="dataForm" status-icon label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="快递公司" prop="shipChannel">
          <el-select v-model="dataForm.shipChannel" placeholder="请选择">
            <el-option v-for="item in ship" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="快递编号" prop="shipSn">
          <el-input v-model="dataForm.shipSn"></el-input>
        </el-form-item>
        <el-form-item label="快递发货时间" prop="shipStartTime">
          <el-date-picker v-model="dataForm.shipStartTime" type="datetime" placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="orderStatus">
          <el-input v-show="false" v-model="dataForm.orderStatus" value="301"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="sendDialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="sendData">确定</el-button>
      </div>
    </el-dialog>

    <!-- 收货对话框 -->
    <el-dialog title="收货" :visible.sync="recvDialogFormVisible">
      <el-form ref="orderForm" :model="dataForm" status-icon label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="快递公司" prop="shipChannel">
          <el-input disabled v-model="dataForm.shipChannel"></el-input>
        </el-form-item>
        <el-form-item label="快递编号" prop="shipSn">
          <el-input disabled v-model="dataForm.shipSn"></el-input>
        </el-form-item>
        <el-form-item label="快递发货时间" prop="shipStartTime">
          <el-date-picker disabled v-model="dataForm.shipStartTime" type="datetime" placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="快递收货时间" prop="shipEndTime">
          <el-date-picker v-model="dataForm.shipEndTime" type="datetime" placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="recvDialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="recvData">确定</el-button>
      </div>
    </el-dialog>

    <!-- 订单详情对话框  可以修改地址信息 -->
    <el-dialog title="订单详情" :visible.sync="orderDialogFormVisible">
      <el-form ref="orderDetail" :model="detail" status-icon label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="购买用户" prop="username">
          <el-input v-model="detail.username"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="mobile">
          <el-input v-model="detail.mobile"></el-input>
        </el-form-item>
        <el-form-item label="订单内容" prop="goods">
          <li v-for="(item, index) in detail.goods" v-bind:key="item.id">
            {{ index + 1 }} - {{ item.goodsName }} - {{ item.goodsSpecificationValues }} - ×{{ item.number }}
          </li>
        </el-form-item>
        <el-form-item label="收货地址" prop="address">
          <el-input v-model="detail.address"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="orderDialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateAddress">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 200px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
}
</style>

<script>
import { listOrder, updateOrder, orderDetail, updateDetail } from '@/api/order'
import { refound } from '@/api/wx'
import waves from '@/directive/waves' // 水波纹指令

export default {
  name: 'Order',
  directives: {
    waves
  },
  data() {
    return {
      list: undefined,
      total: undefined,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        id: undefined,
        name: undefined,
        sort: '+id',
        orderStatus: undefined,
        mobile: undefined,
        consignee: undefined
      },
      ship: [
        { label: '顺丰速运', value: 'SFEXPRESS' },
        { label: '申通快运', value: 'STO' },
        { label: '中通快运', value: 'ZTO' },
        { label: '圆通快运', value: 'YTO' },
        { label: '韵达快运', value: 'YUNDA' },
        { label: '邮政包裹', value: 'CHINAPOST' }
      ],
      status: [
        { label: '全部', value: '' },
        { label: '未付款', value: '101' },
        { label: '已付款', value: '201' },
        { label: '已发货', value: '301' },
        { label: '申请退款', value: '202' },
        { label: '已退款', value: '203' },
        { label: '已收货', value: '401' },
        { label: '已收货（系统）', value: '402' },
        { label: '已评论', value: '403' },
        { label: '已取消', value: '102' },
        { label: '已取消(系统)', value: '103' }
      ],
      dataForm: {
        id: undefined,
        shipChannel: undefined,
        shipSn: undefined,
        shipStartTime: undefined,
        shipEndTime: undefined
      },
      orderForm: {
        orderId: undefined,

        goods: {}
      },
      address: undefined,
      detail: {
        id: undefined,
        goods: {},
        username: undefined,
        mobile: undefined
      },
      sendDialogFormVisible: false,
      recvDialogFormVisible: false,
      orderDialogFormVisible: false,
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      listOrder(this.listQuery)
        .then(response => {
          console.log(response.data.data.items)
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    resetForm(row) {
      this.dataForm.id = row.id
      this.dataForm.shipChannel = row.shipChannel
      this.dataForm.shipSn = row.shipSn
      this.dataForm.shipStartTime = row.shipStartTime
      this.dataForm.shipEndTime = row.shipEndTime
    },
    orderDetail(row) {
      this.listLoading = true
      orderDetail(row.id)
        .then(response => {
          this.detail.id = row.id
          this.detail.goods = response.data.data.goods
          this.detail.username = row.consignee
          this.detail.mobile = row.mobile
          this.detail.address = row.address
          this.listLoading = false
          this.orderDialogFormVisible = true
        })
        .catch(() => {
          this.goods = {}
          this.user = {}
          this.listLoading = false
        })
    },
    updateAddress() {
      this.$refs['orderDetail'].validate(valid => {
        if (valid) {
          updateDetail(this.detail).then(response => {
            const updatedOrder = response.data.data
            for (const v of this.list) {
              if (v.id === updatedOrder.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, updatedOrder)
                break
              }
            }
            this.orderDialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleSend(row) {
      this.resetForm(row)
      this.sendDialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    sendData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.dataForm.orderStatus = '301'
          updateOrder(this.dataForm).then(response => {
            const updatedOrder = response.data.data
            for (const v of this.list) {
              if (v.id === updatedOrder.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, updatedOrder)
                break
              }
            }
            this.sendDialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleRefound(row) {
      this.$confirm('此操作将对该笔交易进行退款, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          refound(row).then(response => {
            console.log(response.data.errno !== '0')
            console.log(response.data.errno)
            console.log(response.data)
            if (response.data.errno !== 0) {
              this.$notify({
                title: '失败',
                message: response.data.errmsg,
                type: 'error',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '成功',
                message: '退款成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            }
          })
        })
        .catch(() => {})
    },
    handleRecv(row) {
      this.resetForm(row)
      this.recvDialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['orderForm'].clearValidate()
      })
    },
    recvData() {
      this.$refs['orderForm'].validate(valid => {
        if (valid) {
          this.dataForm.orderStatus = '402'
          updateOrder(this.dataForm).then(response => {
            const updatedOrder = response.data.data
            for (const v of this.list) {
              if (v.id === updatedOrder.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, updatedOrder)
                break
              }
            }
            this.recvDialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          '订单ID',
          '订单编号',
          '用户ID',
          '订单状态',
          '是否删除',
          '收货人',
          '收货联系电话',
          '收货地址'
        ]
        const filterVal = [
          'id',
          'orderSn',
          'userId',
          'orderStatis',
          'isDelete',
          'consignee',
          'mobile',
          'address'
        ]
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '订单信息')
        this.downloadLoading = false
      })
    }
  }
}
</script>
